package com.xuan.yubi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class HelloProducer {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        // 创建管理连接的工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置 RabbitMq 节点的地址
        factory.setHost("localhost");
        // 建立连接并在使用完毕后自动关闭连接(生产者只需在要发消息时保持连接的建立)
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 正式发送消息前必须先声明要发送的队列，如果队列不存在才会创建它
            // 注意：如果队列已存在，在其他地方声明该队列时参数必须一致，否则会报错
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            Scanner in = new Scanner(System.in);
            while (in.hasNext()) {
                String message = in.next();
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
                System.out.println(" [x] Sent '" + message + "'");
            }
        }
    }
}